#!groovy

@Library('jenkinslib@master') _

def dingmes  = new org.devops.ding()
def k8s = new org.devops.kubernetes()
def model = new org.devops.modules()
def nginx_conf = new org.devops.nginx_server()
def tools = new org.devops.tools()
def workdir = ''
def pronames = ''
def harbor_name = ''
//代码作者
def Author = ''
//更新记录(3条)
def ChangeLog = ''
//gitlab仓库地址
String srcUrl = "${env.srcUrl}"
srcUrl = srcUrl.split("\\(")[0].trim()
//仓库分支
String branchName = "${env.branchName}"
//微服务名称
String proName = "${env.proName}"
proName = proName.split("\\(")[0].trim()
//项目名称
String proJectname = "${env.project}"
//docker file
String dockerinfo = ""
//容器端口
String port = ""
//pipeline
pipeline{
    agent any    
    stages{

       stage("GetCode"){
            steps{
                script{
                        workdir = srcUrl.split('/')[-1].split('.git')[0]
                        if(!workdir) {
                            println "获取工作目录失败"
                            exit()
                        }
                        tools.PrintMes("获取代码","green")
                        checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], 
                        doGenerateSubmoduleConfigurations: false, 
                        extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: "${workdir}"]], 
                        submoduleCfg: [], 
                        userRemoteConfigs: [[credentialsId: '87886427-ebc2-4f45-8921-dcf38f80867e', url: "${srcUrl}"]]])
                        //代码作者
                        res = sh returnStdout: true ,script: "cd ${workdir}/${proName} && git log -1|grep Author |awk '{print \$2}'"
                        Author = res.trim()
                        //更新记录(5条)
                        tmp_shell="""
                            cd ${workdir}/${proName}
                            git log -3 |awk '!/^\$/' |awk '/^Author|^commit/ {next}{printf "%s\\n",\$0}'
                        """
                        res = sh returnStdout: true ,script: "${tmp_shell}"
                        ChangeLog = res.trim()
                        pronames = model.pronames(proName,workdir)
                }
            }
        }
        /*
        stage('SonarQube analysis') {
            steps {
                script {
                    tools.PrintMes("开始代码检查","green")
                    withSonarQubeEnv('SonarQube') {
                    // Optionally use a Maven environment you've configured already
                    sh "cd ${workdir} && cd ${proName} && ${mvn_com} sonar:sonar -Dsonar.projectKey=helloworld -Dsonar.java.binaries=target/sonar  -Dsonar.host.url=http://172.16.1.108:9000 -Dsonar.login=3fc0c5d905cd0fa0c32ec9f7dab0f71c5ccb7964"
                  }
                }
            }
        }
        stage("Quality Gate") {
            steps {
                script {
                    sleep(15)
                    // Parameter indicates whether to set pipeline to UNSTABLE if Quality Gate fails
                    // true = set pipeline to UNSTABLE, false = don't
                     //   waitForQualityGate abortPipeline: true
                        def qg = waitForQualityGate()
                        if (qg.status != 'OK') {
                            echo("代码检查没有通过 ❌")
                            failure
                        }
                        echo("代码检查通过😄  😄  ")
                    }
                }
            }
        */
        stage("Build&Test"){
            //临时中断调试
            /*
            input {
                message "临时中断调试"
                ok "调试结束"
                submitter "admin,anthony"
                parameters {
                    string(name: 'PERSON', defaultValue: 'Mr Anthony', description: '如需取消调试,请修改代码')
                }
            }
            */
            steps{
                script{
                    tools.PrintMes("执行npm编译","green")
                    //下载nginx conf 配置文件
                    nginxconf = model.nginx_conf()
                    //创建临时目录
                    sh "mkdir -p ${workdir}/${proName}/jenkins_tmp"
                    writeFile(file: "${workdir}/${proName}/jenkins_tmp/nginx.conf", text: "${nginxconf} ", encoding: "UTF-8")
                     //清除已有dist文件
                    sh "cd ${workdir} && cd ${proName} && cd jenkins_tmp && rm -rf dist"
                    //分仓库编译-nginx配置分离
                    if (workdir=="esignservice-app"){
                        sh "cd ${workdir} && cd ${proName} && npm install"
                        sh "cd ${workdir} && cd ${proName} && npm run build:h5"
                        //针对当前仓库的dockerfile
                        dockerinfo = model.dockfile_before("dist/build/h5")
                    }else if(workdir=="esign-operation-platform-web"){
                        //重置nginx conf 配置文件--运营
                        nginxconf = model.yun_ying_nginx_conf()
                        sh "cd ${workdir} && cd ${proName} && npm install"
                        writeFile(file: "${workdir}/${proName}/jenkins_tmp/nginx.conf", text: "${nginxconf} ", encoding: "UTF-8")
                        sh "cd ${workdir} && cd ${proName} && npm run build"
                    }else if(workdir=="esign-workflow-web"){
                        dockerinfo = model.dockfile_before()
                        config = nginx_conf.esign_workflow_web()
                        nginxconf = model.nginx_configs(config.trim())
                        writeFile(file: "${workdir}/${proName}/jenkins_tmp/nginx.conf", text: "${nginxconf} ", encoding: "UTF-8")
                        sh "cd ${workdir} && cd ${proName} && cnpm install"
                        sh "cd ${workdir} && cd ${proName} && npm run build:prod"
                    }else if(workdir=="esign-auth-web"){
                        dockerinfo = model.dockfile_before()
                        config = nginx_conf.esign_auth_web()
                        nginxconf = model.nginx_configs(config.trim())
                        writeFile(file: "${workdir}/${proName}/jenkins_tmp/nginx.conf", text: "${nginxconf} ", encoding: "UTF-8")
                    }else{
                        dockerinfo = model.dockfile_before()
                        //cnpm
                        sh "cd ${workdir} && cd ${proName} && cnpm install"
                        //编译
                        out=sh(script:"cd ${workdir} && cd ${proName} && npm run build:prod",returnStatus:true)
                        //临时判断仓库替换nginx配置文件
                        workdir = srcUrl.split('/')[-1].split('.git')[0]
                        if(workdir == "esign-saas-web"){
                                //下载nginx conf 配置文件
                            nginxconf = model.pangu_nginx_conf()
                            writeFile(file: "${workdir}/${proName}/jenkins_tmp/nginx.conf", text: "${nginxconf} ", encoding: "UTF-8")
                        }
                    }
                    //将dist文件放入临时目录
                    sh "cp -rf ${workdir}/${proName}/dist ${workdir}/${proName}/jenkins_tmp/"
                }
            }
       }
       //构建镜像&&上传
        stage("BuildImages"){
            steps{
                script{
                    tools.PrintMes("下载Dockfile","green")
                    writeFile(file: "${workdir}/${proName}/jenkins_tmp/Dockerfile", text: "${dockerinfo} ", encoding: "UTF-8")
                    tools.PrintMes("构建上传镜像","green")
                    def HARBOR_URL = "harbor.ebcall.com"
                    def username = "admin"
                    def password = "cfXoldg71ODYhqnT"
                    result = sh returnStdout: true ,script: "cd ${workdir} && cd ${proName} && git describe --tags"
                    result = result.replace('\n','')
                    result = result.trim()
                    if (!result){
                        println '当前分支无tag标签'
                    }
                    //判断./情况
                    pronames = model.pronames(proName,workdir)
                    def random = new Date().format('ss') + "${env.BUILD_ID}"
                    harbor_name = "${HARBOR_URL}/${proJectname}/${pronames}:${result}-${random}"
                    sh """
                        cd ${workdir}
                        cd ${proName}/jenkins_tmp
                        docker login -u ${username} -p ${password}  ${HARBOR_URL}
                        sleep 1
                        docker build -t ${HARBOR_URL}/${proJectname}/${pronames}:`git describe --tags`-${random} .
                        sleep 1
                        docker push ${HARBOR_URL}/${proJectname}/${pronames}:`git describe --tags`-${random}
                        sleep 1
                        docker rmi ${HARBOR_URL}/${proJectname}/${pronames}:`git describe --tags`-${random}
                      """
                    }
                }
            }
        //部署检测
        stage("k8s_check"){
            steps{
                script{
                    tools.PrintMes("检测存在状态","green")
                      //deployment status
                      result = k8s.GetDeployment(proJectname,pronames)
                      if (result != '0') {
                            k8s.UpdateDeployment(proJectname,pronames,model.deployment(pronames,harbor_name,proJectname))
                            tools.PrintMes("镜像更新成功","blue")
                      }else {
                            tools.PrintMes("发布应用测试","green")
                            //修改deployment文件
                            //proName
                            result = model.deployment(pronames,harbor_name,proJectname)
                            //deployment创建
                            k8s.CreateDeployment("${proJectname}","null",result)
                            sleep 5
                            result = model.Services(pronames,proJectname)
                            //服务创建
                            k8s.CreateServices("${proJectname}",pronames,result)
                            //获取Service
                            result = k8s.GetServices("${proJectname}",pronames)
                      }
                    }
                }
            }
        }
        post{
            success{
                script{
                    tools.PrintMes("========pipeline executed successfully========",'green')
                    dingmes.HttpReq(pronames,'null',"构建成功 ✅ ",Author,ChangeLog,pronames)
                }
            }
            failure{
                script{
                    tools.PrintMes("========pipeline execution failed========",'red')
                    dingmes.HttpReq(pronames,'null',"构建失败 ❌",Author,ChangeLog,pronames,"请查看控制台")
                }
            }
            unstable{
                script{
                    tools.PrintMes("========pipeline execution unstable========",'red')
                    dingmes.HttpReq(pronames,'null',"构建失败 ❌",Author,ChangeLog,pronames,"不稳定异常")
                }
            }
            aborted{
                script{
                    tools.PrintMes("========pipeline execution aborted========",'blue')
                    dingmes.HttpReq(pronames,ImageTag,"构建失败 ❌",Author,ChangeLog,pronames,"暂停或中断")
                }
            }
        }
}
